package org.ilong.consumer.controller;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.ilong.commons.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.ls.LSInput;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * TOOD
 *
 * @author long
 * @date 2020-07-21 15:54
 */
@RestController
public class UseHelloController {

    @Autowired
    DiscoveryClient discoveryClient;

 /*   @GetMapping("/hello1")
    public String hello1(){
        HttpURLConnection con=null;
        try {
            URL url=new URL("http://localhost:1113/hello");
            if(con.getResponseCode()==200){
                 BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                 String s=br.readLine();
                 br.close();
                 return s;
            }

        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return "error";

    }
*/

  /*  @GetMapping("/hello2")
    public String hello2(){
        List<ServiceInstance> list = discoveryClient.getInstances("provider");
         ServiceInstance instance = list.get(0);
         String host = instance.getHost();
         int port = instance.getPort();
         StringBuffer sb=new StringBuffer();
         sb.append("http://")
                 .append(host)
                 .append(":")
                 .append(port)
                 .append("/hello");
         HttpURLConnection con=null;
        try {

            URL url=new URL(sb.toString());
            con =(HttpURLConnection)url.openConnection();
            if(con.getResponseCode()==200){
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String s=br.readLine();
                br.close();
                return s;
            }

        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return "error";

    }
*/
  @Autowired
  @Qualifier("restTemplateOne")
  RestTemplate restTemplateOne;


    public String hello2(){
        List<ServiceInstance> list = discoveryClient.getInstances("provider");
        ServiceInstance instance = list.get(0);
        String host = instance.getHost();
        int port = instance.getPort();
        StringBuffer sb=new StringBuffer();
        sb.append("http://")
                .append(host)
                .append(":")
                .append(port)
                .append("/hello");
       String s=restTemplateOne.getForObject(sb.toString(),String.class);
        return s;

    }

  int count=0;
    @GetMapping("/hello3")
    public String hello3(){

        List<ServiceInstance> list = discoveryClient.getInstances("provider");
        ServiceInstance instance = list.get((count++)%list.size());
        String host = instance.getHost();
        int port = instance.getPort();
        StringBuffer sb=new StringBuffer();
        sb.append("http://")
                .append(host)
                .append(":")
                .append(port)
                .append("/hello");
        HttpURLConnection con=null;
        try {

            URL url=new URL(sb.toString());
            con =(HttpURLConnection)url.openConnection();
            if(con.getResponseCode()==200){
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String s=br.readLine();
                br.close();
                return s;
            }

        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return "error";

    }

    @Autowired
    @Qualifier("restTemplate")
    RestTemplate restTemplate;
    @GetMapping("/hello4")
    public String hello4(){


        return restTemplate.getForObject("http://provider/hello",String.class);

    }

    @GetMapping("/hello5")
    public void hello5(){
         String s1 = restTemplate.getForObject("http://provider/hello2?name={1}",
                 String.class,"ilong");
        System.out.println(s1);
         ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://provider/hello2?name={1}", String.class, "ilong");
         String body = responseEntity.getBody();
        System.out.println("body:"+body);
         HttpStatus statusCode = responseEntity.getStatusCode();
        System.out.println("HttpStatus:"+statusCode);
         int statusCodeValue = responseEntity.getStatusCodeValue();
        System.out.println("statusCodeValue:"+statusCodeValue);
         HttpHeaders headers = responseEntity.getHeaders();
         Set<String> keySet = headers.keySet();
        System.out.println("===============header================");
        for (String s : keySet) {
            System.out.println(s+":"+headers.get(s));
        }
    }

    @GetMapping("/hello6")
    public void hello6() throws UnsupportedEncodingException {
         String s1 = restTemplate.getForObject("http://provider/hello2?name={1}", String.class, "ilong");
         System.out.println(s1);
         HashMap<Object, Object> map = new HashMap<>();
         map.put("name","zhangsan");
         s1=restTemplate.getForObject("http://provider/hello2?name={name}",String.class,map);
         System.out.println(s1);
         String  url="http://provider/hello2?name="+ URLEncoder.encode("张三","UTF-8");
         URI uri= URI.create(url);
          s1 = restTemplate.getForObject(uri, String.class);
         System.out.println(s1);
    }

    @GetMapping("/hello7")
    public void hello7(){
        MultiValueMap<String,Object> map=new LinkedMultiValueMap<>();
        map.add("username","ilong");
        map.add("password","123");
        map.add("id",99);
        User user = restTemplate.postForObject("http://provider/user1", map, User.class);
        System.out.println(user);
        user.setId(98);
        user = restTemplate.postForObject("http://provider/user2", user, User.class);
        System.out.println(user);
    }

    @GetMapping("/hello8")
    public void hello8(){
        MultiValueMap<String,Object> map=new LinkedMultiValueMap<>();
        map.add("username","ilong");
        map.add("password","123");
        map.add("id",99);
        URI uri = restTemplate.postForLocation("http://provider/register", map);
        System.out.println(uri);
        String s = restTemplate.getForObject(uri, String.class);
        System.out.println(s);
    }

}
